package com.cloudpark.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.cloudpark.common.util.Constants;
import com.cloudpark.common.util.JsonBinder;
import com.cloudpark.common.util.MessageUtil;
import com.cloudpark.common.util.ObjectUtil;
import com.cloudpark.common.util.Pagination;
import com.cloudpark.model.entity.AdminUser;
import com.cloudpark.model.entity.User;
import com.cloudpark.service.UserService;
import com.google.common.collect.Maps;

@Controller
@RequestMapping("/system")
public class SystemController extends BaseController {

	private static final Logger log = Logger.getLogger(SystemController.class);
	
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/api/{msg}", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView say(@PathVariable(value = "msg") String msg, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("home.jsp");
        User user = userService.findUserById(1l);
        String name = user.getNickname();
        System.out.println(name);
        System.out.println("sessionId = " + request.getSession().getId());
        return mv;
    }

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    public ModelAndView user(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("system/user.jsp");
        initMenu(request, response);
        return mv;
    }
    
    @RequestMapping(value = "/queryUserList", method = RequestMethod.POST)
    @ResponseBody
    public String queryUserList(HttpServletRequest request,
            @RequestParam(value = "start", defaultValue = "0") int start,
            @RequestParam(value = "length", defaultValue = "10") int length, @RequestParam(value = "draw") int draw,
            HttpServletResponse response) {
        String result = "";
        try {
            AdminUser adminUser = isSessionExpire(request, response);
            String nickname = request.getParameter("nickname");
            Map<String, String> params = new HashMap<String, String>();
            if (ObjectUtil.isNotBlank(nickname)) {
                params.put("nickname", nickname);
            }
            Pagination page = userService.queryUserList(params, start, length, adminUser.getEstateId());
            JsonBinder jsonBinder = JsonBinder.buildBinder(true);
            result = jsonBinder.toJSONDataTables(page, draw, 
            		new String[] { "openId", "nickname", "status", "createdTime", "wechatName" });
        } catch (Exception e) {
            log.error("query user list error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }


    @RequestMapping(value = "/role", method = RequestMethod.GET)
    public ModelAndView role(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("system/role.jsp");
        initMenu(request, response);
        return mv;
    }
    
    @RequestMapping(value = "/queryRoleList", method = RequestMethod.POST)
    @ResponseBody
    public String queryRoleList(HttpServletRequest request,
            @RequestParam(value = "start", defaultValue = "0") int start,
            @RequestParam(value = "length", defaultValue = "10") int length, @RequestParam(value = "draw") int draw,
            HttpServletResponse response) {
        String result = "";
        try {
            AdminUser adminUser = isSessionExpire(request, response);
            String name = request.getParameter("name");
            Map<String, String> params = new HashMap<String, String>();
            if (ObjectUtil.isNotBlank(name)) {
                params.put("name", name);
            }
            Pagination page = userService.queryRoleList(params, start, length, adminUser.getEstateId());
            JsonBinder jsonBinder = JsonBinder.buildBinder(true);
            result = jsonBinder.toJSONDataTables(page, draw, 
            		new String[] { "id", "name", "remark"});
        } catch (Exception e) {
            log.error("query role list error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }
    
    @RequestMapping(value = "/queryRoleOptions", method = RequestMethod.POST)
    @ResponseBody
    public String queryRoleOptions(HttpServletRequest request,
            HttpServletResponse response) {
    	String result = "";
    	Map<String, Object> map = Maps.newHashMap();
        try {
        	AdminUser adminUser = isSessionExpire(request, response);
        	String options = userService.queryRoleOptions(adminUser.getEstateId());
        	map.put("code", Constants.OK);
        	map.put("options", options);
        	result = JSON.toJSONString(map);
        } catch (Exception e) {
            log.error("query role options error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }

    @RequestMapping(value = "/adminUser", method = RequestMethod.GET)
    public ModelAndView adminUser(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("system/adminUser.jsp");
        initMenu(request, response);
        return mv;
    }
    
    @RequestMapping(value = "/queryAdminUserList", method = RequestMethod.POST)
    @ResponseBody
    public String queryAdminUserList(HttpServletRequest request,
            @RequestParam(value = "start", defaultValue = "0") int start,
            @RequestParam(value = "length", defaultValue = "10") int length, @RequestParam(value = "draw") int draw,
            HttpServletResponse response) {
        String result = "";
        try {
            AdminUser adminUser = isSessionExpire(request, response);
            String name = request.getParameter("name");
            String account = request.getParameter("account");
            Map<String, String> params = new HashMap<String, String>();
            if (ObjectUtil.isNotBlank(name)) {
                params.put("name", name);
            }
            if (ObjectUtil.isNotBlank(account)) {
            	params.put("account", account);
            }
            Pagination page = userService.queryAdminUserList(params, start, length, adminUser.getEstateId());
            JsonBinder jsonBinder = JsonBinder.buildBinder(true);
            result = jsonBinder.toJSONDataTables(page, draw, 
            		new String[] { "id", "name", "account", "createdTime", "roleId"});
        } catch (Exception e) {
            log.error("query admin user list error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }
    
    @RequestMapping(value = "/saveOrUpdateAdminUser", method = RequestMethod.POST)
    @ResponseBody
    public String saveOrUpdateAdminUser(HttpServletRequest request,
            HttpServletResponse response) {
        String result = "";
        try {
            AdminUser adminUser = isSessionExpire(request, response);
            String adminUserId = request.getParameter("adminUserId");
            String userName = request.getParameter("userName");
            String userAccount = request.getParameter("userAccount");
            String roleId = request.getParameter("roleId");
            if (ObjectUtil.isBlank(userName)) {
            	result = MessageUtil.error("员工姓名不能为空");
            	return result;
            }
            if (ObjectUtil.isBlank(userAccount)) {
            	result = MessageUtil.error("用户名不能为空");
            	return result;
            }
            if (ObjectUtil.isBlank(roleId)) {
            	result = MessageUtil.error("角色不能为空");
            	return result;
            }
            // 校验用户名重名
            List<AdminUser> adminUsers = userService.findByAccountWithEstateId(userAccount, adminUser.getEstateId());
            if (ObjectUtil.isNotBlank(adminUsers)) {
            	if (ObjectUtil.isBlank(adminUserId)) {
            		result = MessageUtil.error("该用户名已存在");
                	return result;
                } else {
                	if (Long.valueOf(adminUserId).longValue() != adminUsers.get(0).getId().longValue()) {
                		result = MessageUtil.error("该用户名已存在");
                    	return result;
                	}
                }
            }
            userService.saveOrUpdateAdminUser(adminUserId, userName, userAccount, roleId, adminUser.getEstateId());
            result = MessageUtil.success();
        } catch (Exception e) {
            log.error("save or update admin user error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }

    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public String updatePassword(HttpServletRequest request,
            HttpServletResponse response) {
        String result = "";
        try {
            AdminUser adminUser = isSessionExpire(request, response);
            String oldPwd = request.getParameter("oldPwd");
            String newPwd = request.getParameter("newPwd");
            if (ObjectUtil.isBlank(oldPwd)) {
            	result = MessageUtil.error("旧密码不能为空");
            	return result;
            }
            if (ObjectUtil.isBlank(newPwd)) {
            	result = MessageUtil.error("新密码不能为空");
            	return result;
            }
            // 校验用户名重名
        	if (DigestUtils.sha256Hex(oldPwd).equals(adminUser.getPassword())) {
        		adminUser.setPassword(DigestUtils.sha256Hex(newPwd));
        		userService.saveAdminUser(adminUser);
            } else {
            	result = MessageUtil.error("旧密码不匹配");
            	return result;
            }
        	result = MessageUtil.success();
        } catch (Exception e) {
            log.error("update admin user password error :", e);
            result = MessageUtil.error("服务器忙!");
        }
        return result;
    }
}
